package com.liuyucheng.idea_springboot.controller;

import com.liuyucheng.idea_springboot.service.EChartsService;
import com.liuyucheng.idea_springboot.util.IOUtil;
import com.liuyucheng.idea_springboot.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/echarts")
public class EChartsController {
    private EChartsService service;

    @Autowired
    public void setService(EChartsService service) {
        this.service = service;
    }

    @RequestMapping(value = "/getDataBar",method = RequestMethod.POST,consumes = {MediaType.ALL_VALUE})
    public ResultUtil getDataBar(@RequestBody Map<String,Object> paraMap) {
        log.info("进入到getDataBar,打印日志");
        int id = (int) paraMap.get("id");

        log.info("这是测试热部署的打印日志==========>");
        invokeDevtool2("测试新增方法的热部署");
        return service.getDataBar(id);
    }

    private void invokeDevtool2(String info) {
        log.info(info);
    }

    @RequestMapping(value = "/readDs",method = RequestMethod.POST,consumes = {MediaType.ALL_VALUE})
    public ResultUtil readDs() {
        return service.readDs();
    }

    @RequestMapping(value = "/plusOne",method = RequestMethod.POST,consumes = {MediaType.ALL_VALUE})
    public ResultUtil plusOne() {
        ResultUtil res = null;
        try {
            res = service.plusOne();
        } catch (Exception e) {
            return ResultUtil.success(e.getMessage());
        }
        return res;
    }

    /**
     * 前端预览图片接口
     * @param response response
     * @throws IOException 异常
     */
    @GetMapping("/getImage")
    public void image(HttpServletResponse response) throws IOException {
        String path = ResourceUtils.getURL("classpath:file/image/325497.jpg").getPath();
        try(InputStream input = new FileInputStream(path);
            OutputStream output = response.getOutputStream()){
            output.write(IOUtil.read(input));
        }
    }

}
